import { Injectable } from "@angular/core";
import { MyhttpService } from "./myhttp.service";
import { LocalStorageService } from "./local-storage-service";
import CryptoJS from 'crypto-js';
import { SharedService } from "./shared-service";

declare var $: any;
declare var swal: any;

@Injectable({
  providedIn: 'root',
})
export class CommService {
  public topH: number = 50;
  public topmenuH: number = 50;
  public HOST: string = location.protocol + "//" + location.host + "/platform";
  public HOST2: string = location.protocol + "//" + location.host;
  public serverurl: string = location.hostname;
  /**
   * token
   * @param {string} t
   */
  public token: string = "";
  public signkey: string;
  public appId: string = "zjskszhpt"; // 常量
  public secret: string = "48ef0ae898084a638dd11ce0f5af5d09"; // 常量
  public ocxobj1: any; // 平台中的一个控件对象
  public ocxobj2: any;
  public ocxobj3: any;
  public userinfo: any;
  private key: string = "7ed0a55691534aa8a9a692d373deeee8";
  private iv: string = "6bSWAnEG/f2onZ7S";
  public applicationId: string = "20051114403600889018273302699008";
  //public uploadFileurl = "http://173.0.0.11:7979/";    // 浙江省考院
  //public uploadFileurl = "http://101.71.249.36:7979/";    // 浙江省考院外网
  //public uploadFileurl = "http://172.16.15.228:7979/";    // 山西省

  // public uploadFileurl = "http://47.111.5.196:7979/";    // 阿里云
  // public uploadFileurl = "https://test.techhero.vip:18085/"
  // public uploadFileurl = `${location.protocol}//${location.hostname}:7979/`;    // 阿里云 相对
  //public uploadFileurl = "http://192.168.156.167:7979/";    // 郑州 167

  // public uploadFileurl = "http://127.0.0.1:7979/";


  //public uploadFileurl = "http://192.168.157.37:7979/";  // 37
  // public uploadFileurl = "https://www.sneac.edu.cn/plateformApi/";    // 陕西


  // public uploadFileurl = "http://101.71.241.116:1179/";    // 杭州考试院

  //public uploadFileurl = "http://119.96.170.205:7979/";    // 湖北平台-----未集成演示用的试卷跟踪
  public uploadFileurl = "https://www.hbjyks.cn:19000/";


  setToken(t: string): void {
    this.token = t;
  }

  getToken(): string {
    return this.token;
  }

  setSignkey(key: string): void {
    this.signkey = key;
  }

  getSignkey(): string {
    return this.signkey;
  }

  /**
   * 根据配置文件获取 系统的信息
   * @param {Function} callback
   */
  getSysmsg(callback: Function): void {
    $.get("myapp_config.json", function (resp) {
      callback(resp);
    });

    callback({
      "name": "sys",
      "sysBase": "42",
      "sysChildren": [],
      "version": "1.0.0.3",
      "Copyright": "2019-2020 浙江省教育考试院",
      "syslogonameb": "logoB33",
      "syslogonames": "logoS33",
      "title": "浙江省教育考试综合管理平台",
      "dependencies": {}
    })
    // callback({
    //   "name": "sys",
    //   "sysBase": "61",
    //   "sysChildren": [],
    //   "version": "1.0.0.3",
    //   "Copyright": "2017-2020 陕西省教育考试院",
    //   "syslogoname": "logo61",
    //   "title": "陕西省国家教育考试综合管理平台",
    //   "dependencies": {
    //   }
    // })
  }

  getSysmsg2(callback: Function): void {
    const daes = this.localstorage.get("sysmsg");
    const daesstr = daes ? this.daesString(daes) : "";
    if (daesstr) {
      callback(JSON.parse(daesstr));
    } else {
      callback(null);
    }
  }

  getPtlx(callback: Function): void {
    this.getSysmsg((resp) => {
      let ptlx: string;
      const sysBase = resp.sysBase;
      if (sysBase == "33") {
        ptlx = "zj";
      } else if (sysBase == "61") {
        ptlx = "sx";
      }
      callback(ptlx);
    })
  }


  getcookie(key: string): string {
    let retstr = "";
    const str = document.cookie; // 获取所有cookie
    const arr = str.split("; "); // ["name=pengpeng", "age=18", "desc=shuai"]
    // 遍历数组, 找出 键===key时的 value值
    for (let i = 0; i < arr.length; i++) {
      const data = arr[i].split("="); // ["name", "pengpeng"]
      if (data[0] === key) {
        // 如果相等, 说明找到了
        retstr = data[1];
      }
    }
    return retstr;
  }


  setOcxobj(ocxobj: any, ocxindex: number): void {
    switch (ocxindex) {
      case 1:
        this.ocxobj1 = ocxobj;
        break;
      case 2:
        this.ocxobj2 = ocxobj;
        break;
      case 3:
        this.ocxobj3 = ocxobj;
        break;
    }
  }

  getOcxobj(ocxindex: number): any {
    let ocxobj: any;
    if (ocxindex === 1) {
      ocxobj = this.ocxobj1;
    } else if (ocxindex === 2) {
      ocxobj = this.ocxobj2;
    } else if (ocxindex === 3) {
      ocxobj = this.ocxobj3;
    }
    return ocxobj;
  }


  /**
   * 获取用户详情
   * @param {Function} callback
   */
  getUserinfo(callback: Function): void {
    const aesuserinfostr = this.localstorage.get('info');
    if (aesuserinfostr) {
      const daesuserifostr = this.daesString(aesuserinfostr);
      this.info("登入用户详情", JSON.parse(daesuserifostr), "");
      callback(JSON.parse(daesuserifostr));
    } else {
      callback({});
    }
  }

  /**
   * 获取控制当前登入用户页面表现的  区别码
   * @param {string} departmentType
   * @param {string} departmentId
   * @param {string} rolelx
   * @returns {string}
   */
  getuserDepartmentFl(departmentType: string, departmentId: string, rolelx: string): string {
    let str = '';
    if (departmentType === 'ksgljg') {
      const departmentIdstr = departmentId.toString();
      const shengcode = departmentIdstr.substring(0, 2);
      const shicode = departmentIdstr.substring(2, 4);
      const xiancode = departmentIdstr.substring(4, 6);
      if (Number(xiancode) * Number(shicode) > 0) {
        str = 'Z3';
      } else {
        if (Number(shicode) > 0) {
          str = 'Z2';
        } else {
          str = 'Z1';
        }
      }
    } else if (departmentType === 'bms') {
      str = 'M';
    } else if (departmentType === 'bzhkd') {
      if (rolelx === 'spxsy') {
        str = 'SPXSY';
      } else {
        str = 'K';
      }
    } else if (departmentType == "pjd") {
      str = 'pjdgly';
    }
    return str;
  }

  getStream(callback: Function): void {
    const streap = this.localstorage.get("stream");
    if (streap) {
      const daesstr = this.daesString(streap);
      this.info("流媒体信息", JSON.parse(daesstr), "");
      callback(JSON.parse(daesstr));
    } else {
      callback({});
    }
  }

  /**
   * 获取 请求url资源共用的5个参数
   * @returns {any}
   */
  getpubbodyParams(): any {
    const msgId = Math.floor(Math.random() * Math.pow(10, 10)); // 消息id号，唯一
    const transChannel = "web";  // 交易通道
    const channelSerialNo = msgId;    //通道流水号 唯一
    const channelTime = this.YMDHMS_get(false); //通道时间   2020-02-19 11:12:30
    const clientIp = "192.168.1.145";  // web所在的客户端的ip
    return {
      msgId: msgId,
      transChannel: transChannel,
      channelSerialNo: channelSerialNo,
      channelTime: channelTime,
      clientIp: clientIp
    }
  }

  /**
   * 获取 请求url资源的头部信息
   * @returns {any}
   */
  getpubheaderParams1(reqobj: any): any {
    const signkey = this.getSignkey();
    let signreqobj = "";
    if (reqobj != null) {
      signreqobj = this.getSignReqobj(signkey, JSON.stringify(reqobj));
    }
    return {
      signkey: signkey,
      signreqobj: signreqobj
    }
  }

  /**
   * 获取 请求url资源的头部信息
   * @returns {any}
   */
  getpubheaderParams2(): any {
    const access_token = this.getToken();
    const Authorization = `Bearer ${access_token}`;
    return {
      access_token: access_token,
      Authorization: Authorization
    }
  }

  /**
   * HmacSHA1 加密
   * @returns {any}
   */
  getSignReqobj(sinkey: string, value: string): any {
    //const result = CryptoJS.HmacSHA1(value, key).toString(CryptoJS.enc.Base64);
    const sha1_result = CryptoJS.HmacSHA1(value, sinkey);
    //console.log("sha1_result", sha1_result);
    //console.log("CryptoJS.enc", CryptoJS.enc);
    const result = CryptoJS.enc.Base64.stringify(sha1_result);
    return result;
  }

  /**
   *  aes 加密数据
   * @param data    ---明文数据
   * @returns {string}---base64密文
   */
  aesString(data: any): string {
    const key = CryptoJS.enc.Utf8.parse(this.key);
    const iv = CryptoJS.enc.Utf8.parse(this.iv);
    const encrypted = CryptoJS.AES.encrypt(data, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
  }

  /**
   * aes 解密
   * @param {string} encrypted   ---- encrypted  --base64密文
   * @returns {string}            ---明文字符串
   */
  daesString(encrypted: string): string {
    const key = CryptoJS.enc.Utf8.parse(this.key);
    const iv = CryptoJS.enc.Utf8.parse(this.iv);
    const decrypted = CryptoJS.AES.decrypt(encrypted, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
  }

  info(arg1: any, arg2: any, arg3: any): void {
    try {
      console.info(arg1, arg2, arg3);
    } catch (e) {

    }

  }

  warn(arg1: any, arg2: any, arg3: any): void {
    try {
      console.warn(arg1, arg2, arg3);
    } catch (e) {

    }
  }

  error(arg1: any, arg2: any, arg3: any): void {
    try {
      console.error(arg1, arg2, arg3);
    } catch (e) {

    }
  }

  log(arg1: any, arg2: any): void {
    try {
      console.log(arg1, arg2);
    } catch (e) {

    }
  }

  /**
   * 处理每个接口的返回数据（拦截器处理过的返回）
   * @param {string} ywflag  get（获取类） put（添加，编辑，删除类）
   * @param {string} url  服务器资源url
   * @param resp  拦截器处理的返回
   * @param callback
   */
  handResponse(ywflag: string, url: string, resp: any, callback: any): void {
    this.unblockUI(false);
    const code = resp.code;  //   200  202[signkey失效]  其他[直接抛出 message]
    if (code === 200) {
      if (ywflag === "get") {
        this.info(url, "----get类接口200返回信息----", resp.result);
        callback(true, resp.result, true);
      } else if (ywflag === "put") {
        this.info(url, "-----put类200提示信息---", resp.message);
        callback(true, resp.message, true);
      }
    } else if (code === 202) {
      this.warn(url, "-----接口signkey失效----", resp.message);
      this.itservice.kwPtPost("manager/getConnToken", {
        "appId": this.appId,
        "secret": this.secret
      }).subscribe(resp => {
        const code = resp.code;
        if (code === 200) {
          const signkey = resp.result.token;
          this.setSignkey(signkey);
          this.localstorage.set("signkey", signkey);
          callback(false, "", true);
        }
      });
    } else {
      //code=99999 或者  resp=[]( catchError中的 return of([]))
      if (ywflag === "get") {
        this.error(url, "-----get类接口code=9999错误返回信息----", resp.message);
        callback(true, resp.message ? resp.message : "signkey缺失", false);
      } else if (ywflag === "put") {
        this.error(url, "------put类code=9999错误提示信息---", resp.message);
        callback(true, resp.message, false);
      }
    }
  }

  /**
   *
   * @returns {boolean}
   * true =ie浏览器
   * false = 不是ie浏览器
   */
  isIE(): boolean {
    return !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
  }

  /**
   * 获取可视图的高度和宽度
   * @returns {any}
   */
  getViewPort(): any {
    if (!('innerWidth' in window)) {
      let e: HTMLElement = document.documentElement || document.body;
      return {
        width: e.clientWidth,
        height: e.clientHeight,
      }
    } else {
      return {
        width: window.innerWidth,
        height: window.innerHeight,
      }
    }
  }

  /**
   * 右上角 收缩topmenu，页面高度的自适应处理
   * @param {string} s  in隐藏 topmenu  out显示topmenu
   * @param {string} t   btn,右上角的按钮  screen f11全屏
   * @returns {number}
   */
  getFitHeight(s: string, t: string): number {
    let h: number = 0;
    if (s == 'in') {
      if (t == 'btn') {
        h = this.getViewPort().height - this.topH;
      } else if (t == 'screen') {
        h = this.getViewPort().height - this.topH - this.topmenuH;
      }
    } else {
      if (t == 'btn') {
        h = this.getViewPort().height - this.topH - this.topmenuH;
      } else if (t == 'screen') {
        h = this.getViewPort().height - this.topH;
      }
    }
    return h;
  }

  /**
   * 获取 没有二级菜单页面的高度
   */
  getPageHeigh(): string {
    const pageheight = this.getViewPort().height - this.topH - this.topmenuH;
    return pageheight + "px";
  }


  /**
   *
   * @param {string} type  ---iframe 嵌套页面的含义
   * @param {number} ifw  ----iframe 的宽度
   * @param {number} ifh  ----iframe 的高度
   * @param {string} ifsrc ----iframe 资源的页面的地址
   * @param pushdata       ---- 往iframe资源页面传递的参数
   * @returns {any}
   */
  initIframePz(type: string, ifw: number, ifh: number, ifsrc: string, pushdata: any): any {
    const that = this;
    const $iframedom = $('<iframe frameborder="0" name="appframe" id="appframe" style="position: absolute;left: 0px;top: 0px;z-index: 1500;"></iframe>');
    $iframedom.attr('src', ifsrc);
    $iframedom.css({
      'width': ifw + 'px',
      'height': ifh + 'px',
      'left': (that.getViewPort().width - ifw) / 2,
      'top': (that.getViewPort().height - ifh) / 2,
      'background-color': 'beige',
      'background-clip': 'padding-box',
      'border': '1px solid rgba(0, 0, 0, .2)',
      'border-radius': '6px',
      'outline': 0,
      'box-shadow': '0 3px 9px rgba(0, 0, 0, .5)',
    });
    // 主入口处动态添加了iframe元素
    $('.main_out').append($iframedom);
    const iframedom = $iframedom[0] as any;
    if (iframedom.attachEvent) {
      iframedom.attachEvent('onload', function () { // IE
        that.readerIfram(type, ifw, ifh, ifsrc, pushdata);
      });
    } else {
      iframedom.onload = function () { // 非IE
        that.readerIfram(type, ifw, ifh, ifsrc, pushdata);
      };
    }
    return $iframedom;
  }

  /**
   * postMessage 方法 传递给 iframe页面资源参数
   * @param {string} type
   * @param {number} ifw
   * @param {number} ifh
   * @param {string} ifsrc
   * @param extradata
   */
  readerIfram(type: string, ifw: number, ifh: number, ifsrc: string, extradata: any): void {
    const pwinParam = {
      w: ifw,
      h: ifh,
      type: type
    };
    if (type == 'helpmsg') {

    }
    window.frames[0].postMessage(JSON.stringify(pwinParam), ifsrc);
  }

  /**
   * 判断 iframe 是否存在
   * @param $iframedom
   * @returns {boolean}
   */
  isframeExist($iframedom: any): boolean {
    if ($iframedom) {
      return $iframedom.css('display') == 'block';
    } else {
      return false;
    }
  }

  /**
   * 给组下的 菜单按照 规定的顺序排序（显示）
   * @param allmenu---有顺序的所有菜单   url字符串
   * @param noorder ---无顺序的权限菜单  对象
   * @returns {any}
   */
  sortMenu(allmenu: any, noorder: any, orderkey): any {
    const retarr: any[] = [];
    allmenu.forEach((url) => {
      noorder.forEach((item) => {
        if (item[orderkey] == url) {
          retarr.push(item)
        }
      });
    })
    return retarr;
  }

  /**
   *
   * @param {string} type
   * primary/info/warning----不同颜色的感叹号
   * success-----绿色对号
   * danger-----红色叉号
   * @param {string} title ---一级提示文本
   * @param {string} text  ---二级提示文本
   * @param {string} czlx ---操作类型，ts--只提示  cz---有回调操作
   */
  myswal(type: string, title: string, text: string, czlx: string, callback: Function): void {
    if (czlx === "ts") {
      // sweetalert
      // const obj = {
      //   title: title,
      //   type: type,
      //   confirmButtonText: "确定"
      // };
      // if (!text) {
      //   obj["text"] = text;
      // }
      // swal(obj);

      // myalert
      this.sharedService.emitChange({
        actiontype: "myalert",
        alerttype: type,
        msg: title,
        msg2: text
      });

    } else if (czlx === "cz") {
      const obj = {
        title: title,
        type: type,
        showCancelButton: true,
        cancelButtonText: "否",
        //confirmButtonClass: "btn-danger",
        confirmButtonText: "是",
        closeOnConfirm: true,
      };
      if (text) {
        obj["text"] = text;
      }
      swal(obj, callback);
    }
  }


  /**
   *  获取码表值
   * @param {string} mbywmcs        码表英文名称，用_ 隔开的
   * @param {Function} callback
   */
  getmbzd(mbywmcs: string, callback: Function): void {
    const url = "ksyw/mb/hccx";
    const mbkeys = mbywmcs.split(";");
    this.itservice.kwPtPost(url, {
      keys: mbkeys
    }).subscribe(resp => {
      this.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            callback(resp.hcmbsjList ? resp.hcmbsjList : [], flag2);
          } else {
            callback(resp, flag2);
          }
        } else {
          this.getmbzd(mbywmcs, callback);
        }
      });
    });
  }


  YMD_get(date: any): string {
    const fullyear = date.getFullYear();
    let fullmonth = date.getMonth() + 1;  // 1-12
    let day = date.getDate();
    if (fullmonth.toString().length < 2) {
      fullmonth = `0${fullmonth}`;
    }
    if (day.toString().length < 2) {
      day = `0${day}`;
    }
    return `${fullyear}-${fullmonth}-${day}`;
  }

  /**
   *
   * @param date  ----------Date对象
   * @returns {string}   yyyymm 格式的字符串
   * @constructor
   */
  YM_get(date: any, type: string): string {
    const fullyear = date.getFullYear();
    let fullmonth = date.getMonth() + 1;  // 1-12
    if (fullmonth.toString().length < 2) {
      fullmonth = `0${fullmonth}`;
    }
    if (type == "separate") {
      return `${fullyear}-${fullmonth}`;
    } else {
      return `${fullyear}${fullmonth}`;
    }
  }


  HMS_get(date: any): string {
    let hour = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    if (hour.toString().length < 2) {
      hour = `0${hour}`;
    }
    if (minutes.toString().length < 2) {
      minutes = `0${minutes}`;
    }
    if (seconds.toString().length < 2) {
      seconds = `0${seconds}`;
    }
    return `${hour}:${minutes}:${seconds}`;
  }

  HM_get(date: any): string {
    let hour = date.getHours();
    let minutes = date.getMinutes();
    if (hour.toString().length < 2) {
      hour = `0${hour}`;
    }
    if (minutes.toString().length < 2) {
      minutes = `0${minutes}`;
    }
    return `${hour}:${minutes}`;
  }

  /**
   * 兼容方法
   * @param {Object} arg
   * arg 存在，必须是合法的时间字符串，比如 'Wed Jul 05 2017 15:03:00 GMT+0800 (中国标准时间)'  或者 数字   2563200(毫秒)
   * arg 不存在，取当前电脑时间的
   */
  YMDHMS_get(arg: any): string {
    let now: any;
    if (arg) {
      now = new Date(arg);
    } else {
      now = new Date();
    }
    const year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minu = now.getMinutes();
    let seconds = now.getSeconds();
    if (month.toString().length < 2) {
      month = `0${month}`;
    }
    if (day.toString().length < 2) {
      day = `0${day}`;
    }
    if (hour.toString().length < 2) {
      hour = `0${hour}`;
    }
    if (minu.toString().length < 2) {
      minu = `0${minu}`;
    }
    if (seconds.toString().length < 2) {
      seconds = `0${seconds}`;
    }
    return `${year}-${month}-${day} ${hour}:${minu}:${seconds}`;
  }

  /**
   *
   * @param {string} timestr  2018-10-12  15:30:20
   * @returns {any} --------ms
   */
  convertTimeToInt(timestr: string): any {
    let result = null;
    if (timestr != null && timestr != "") {
      result = Date.parse(timestr.replace(/-/g, "/"));
    }
    return result;
  };


  /**
   *  string元素数组去重
   * @param arr
   * @returns {any}
   */
  fliterRepeat(arr: any): any[] {
    let retarr = [];
    let o: any = {};
    for (let i = 0; i < arr.length; i++) {
      if (!o[arr[i]]) {
        retarr.push(arr[i]);
        o[arr[i]] = 1;
      }
    }
    return retarr;
  }


  /**
   * @param {string} parentid ---上级的菜单url, 根菜单是"0"
   * @param {string} roleid  ---角色id
   */
  getroleMenus(parentid: string, roleid: string, callback: Function): void {
    const url = "manager/user/getRoleMenuResource";
    this.itservice.kwPtPost(url, {
      parentId: parentid,
      roleId: roleid
    }).subscribe(resp => {
      this.handResponse("get", url, resp, (flag1, resp, flag2) => {
        if (flag1) {
          if (flag2) {
            const roleMenuResourceList = resp.roleMenuResourceList;
            callback(roleMenuResourceList); // object[]
            /**
             * {
             * id---主键
             * code---菜单url
             * name--菜单/按钮名称
             * type--类型  menu--菜单  btn--按钮
             * level-- 层级
             * }
             */
          } else {
            this.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getroleMenus(parentid, roleid, callback);
        }
      });
    });
  }

  /**
   *
   * @param allportbtns---右上角所有按钮
   * @param alltablebtns ---表格操作列中所有按钮
   * @returns {any}
   */
  getroleBtns(allportbtns: any, alltablebtns: any, nowroleid: string, pfrom: string, callback: Function): void {
    alert('原本函数')
    const lmenuid = this.localstorage.get("lmenuid");
    this.getroleMenus(lmenuid, nowroleid, (btns) => {
      if (btns && btns.length) {
        const hasportbtns: any[] = [];
        const hastablebtns: any[] = [];
        btns.forEach((item) => {
          const code = item.code.toString().trim();
          if (allportbtns.indexOf(code) != -1) {
            const btntype = code.split("_")[1];
            hasportbtns.push({
              pfrom: pfrom,
              title: item.name,
              type: btntype,
              show: true
            })
          }
          if (alltablebtns.indexOf(code) != -1) {
            hastablebtns.push(code);
          }
        });
        callback(hasportbtns, hastablebtns);
      } else {
        callback([], []);
      }
    });
  }

  /**
   *
   * @param allportbtns---右上角所有按钮
   * @param alltablebtns ---表格操作列中所有按钮
   * @returns {any}
   */
  getroleBtns_not_permissions(allportbtns: any, alltablebtns: any, pfrom: string, callback: Function): void {

    let hasportbtns: any[] = [];
    let hastablebtns: any[] = [];
    if (allportbtns.length >= 0) {
      allportbtns.forEach(code => {
        const btntype = code.split("_")[1];
        let name = ''
        switch (code.split("_")[1]) {
          case 'dc':
            name = '导出'
            break;
          case 'clN':
            name = '批量处理'
            break;
          case 'add':
            name = '添加'
            break;
          case 'refresh':
            name = '刷新'
            break;
          case 'gpsonN':
            name = '开启gps'
            break;
          case 'gpsoffN':
            name = '关闭gps'
            break;
          case 'plpzcs':
            name = '批量配置电子标签参数'
            break;
          case 'removeN':
            name = '批量删除'
            break;
          case 'dr':
            name = '批量新增'
            break;
          case 'zxt':
            name = '折线图'
            break;
          case 'xtsc':
            name = '生成运送任务'
            break;
          case 'bindgx':
            name = '绑定关联关系'
            break;
          default:
            name = '暂无配置'
        }
        console.log(name);

        hasportbtns.push({
          pfrom: pfrom,
          title: name,
          type: btntype,
          show: true
        })
      });
    }
    if (alltablebtns.length >= 0) {
      alltablebtns.forEach(code2 => {
        hastablebtns.push(code2);
      });
    }
    // callback()
    callback ? callback(hasportbtns, hastablebtns) : null
  }

  /**
   *
   * @param filepath-----服务端生成的附件 filepath
   * @param {string} downloadname-----下载后附件重命名
   */
  downFile(filepath: string, downloadname: string, wjlx: string): void {
    const anchorEl = document.getElementById("downRoom");
    anchorEl.innerHTML = "";
    const _a = document.createElement("a");
    const downpath = this.removeFirst_(filepath);
    _a.setAttribute("href", downpath);
    _a.setAttribute("target", "view_window");
    if (downloadname) {
      const nowObj = new Date();
      const year = nowObj.getFullYear();
      const month = nowObj.getMonth();
      const day = nowObj.getDate();
      const hour = nowObj.getHours();
      const minutes = nowObj.getMinutes();
      const seconds = nowObj.getSeconds();
      // 只有 Firefox 和 Chrome 支持 download 属性。
      // 在 <a> 标签中必须设置 href 属性。
      // 该属性也可以设置一个值来规定下载文件的名称。所允许的值没有限制，浏览器将自动检测正确的文件扩展名并添加到文件 (.img, .pdf, .txt, .html, 等等)。
      _a.setAttribute("download", `${downloadname}${year}${month}${day}${hour}${minutes}${seconds}.${wjlx}`);

    } else {
      let fileName: string = "";
      if (filepath.indexOf("?") != -1) {
        fileName = filepath.substring(filepath.lastIndexOf('/') + 1, filepath.lastIndexOf("?"));
      } else {
        fileName = filepath.substring(filepath.lastIndexOf('/') + 1);
      }
      _a.setAttribute("download", fileName);
    }
    anchorEl.appendChild(_a);
    _a.click();
  }

  blockUI(options: any): void {
    const options1 = $.extend(true, {}, options);
    let html = '';
    if (options1.animateOnly) {
      html = '<div class="loading-message ' + (options1.boxed ? 'loading-message-boxed' : '') + '">' + '<div class="block-spinner-bar"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>' + '</div>';
    } else if (options1.iconOnly) {
      html = '<div class="loading-message ' + (options1.boxed ? 'loading-message-boxed' : '') + '"><i class="fa fa-spinner"></i></div>';
    } else if (options1.textOnly) {
      html = '<div class="loading-message ' + (options1.boxed ? 'loading-message-boxed' : '') + '"><span>&nbsp;&nbsp;' + (options1.message ? options1.message : '加载中...') + '</span></div>';
    } else if (options1.imgOnly) {
      html = '<div class="loading-message ' + (options1.boxed ? 'loading-message-boxed' : '') + '"><img  src=""></div>';
    } else {
      html = '<div class="loading-message ' + (options1.boxed ? 'loading-message-boxed' : '') + '"><i class="fa fa-spinner"></i><span>&nbsp;&nbsp;' + (options1.message ? options1.message : '加载中...') + '</span></div>';
    }
    if (options1.target) { // element blocking
      const el = $(options1.target);
      if (el.height() <= ($(window).height())) {
        options1.cenrerY = true;
      }
      el.block({
        message: html,
        baseZ: options1.zIndex ? options1.zIndex : 1000,
        centerY: options1.cenrerY !== undefined ? options1.cenrerY : false,
        css: {
          top: '10%',
          border: '0',
          padding: '0',
          backgroundColor: 'none'
        },
        overlayCSS: {
          backgroundColor: options1.overlayColor ? options1.overlayColor : '#555',
          opacity: options1.boxed ? 0.05 : 0.1,
          cursor: 'wait'
        }
      });
    } else { // page blocking
      $.blockUI({
        message: html,
        baseZ: options1.zIndex ? options1.zIndex : 1000,
        css: {
          border: '0',
          padding: '0',
          backgroundColor: 'none'
        },
        overlayCSS: {
          backgroundColor: options1.overlayColor ? options1.overlayColor : '#555',
          opacity: options1.boxed ? 0.05 : 0.1,
          cursor: 'wait'
        }
      });
    }
  }

  unblockUI(target: any): void {
    if (target) {
      $(target).unblock({
        onUnblock: function () {
          $(target).css('position', '');
          $(target).css('zoom', '');
        }
      });
    } else {
      $.unblockUI();
    }
  }

  /***
   * 数组根据某个键值排序   字符编码
   * @param arr
   * @param key
   * @returns {any}
   */
  sortArr(arr: any, key: any, order: string): any[] {
    if (arr.length == 0) {
      return [];
    }
    return arr.sort(function (a, b) {
      if (order == "asc") {
        return a[key] - b[key];
      } else if (order == "desc") {
        return b[key] - a[key];
      }
    });
  }

  /**
   * 处理成  jstree 树结构的数据
   * @param {Object} data
   * @param {Object} pid
   */
  createjstree(data: any, pid: string): any[] {
    const result: any[] = [];
    let temp: any;
    for (let i = 0; i < data.length; i++) {
      if (data[i].parentid == pid) {
        const obj: Object = {
          id: data[i].id,
          text: data[i].name,
          type: data[i].type ? data[i].type : "",
          state: {
            selected: false
          }
        };
        if (pid === "#") {
          obj["state"]["opened"] = true;
        }
        temp = this.createjstree(data, data[i].id);
        if (temp.length > 0) {
          obj["children"] = temp;
        } else {
          obj["state"].selected = (data[i].ischecked == "1") ? true : false;
        }
        result.push(obj);
      }
    }
    return result;
  }

  /**
   * @param {number} number  290394
   * @returns {string} 29万394
   */
  thousandN_get(num: number): string {
    let retstr: string = num.toString();
    if (num >= 10000) {
      const wan = num / 10000;
      const wanarr = wan.toString().split(".");
      if (wanarr.length == 1) {
        retstr = wanarr[0] + "万";
      } else {
        retstr = wanarr[0] + "万" + Number(wanarr[1]);
      }
    }
    return retstr;
  }

  /**
   * 下载路径使用
   * @param {string} str
   * @returns {string}
   * @private
   */
  removeFirst_(str: string): string {
    const firtcode = str.substring(0, 1);
    if (firtcode == "/") {
      return str.substring(1);
    } else {
      return str;
    }
  }

  /**
   * 判断 v 是否在 arr中是重复的
   * @param arr------判断是有重复元素的数组【可能存在重复】
   * @param index----arr长度一致的，循环的索引，从0开始
   * @param v    -----arr中的元素
   * @returns {boolean}
   */
  isrepeat(arr: any, index: number, v: string): boolean {
    let retflag = false;
    const a = arr.slice(0, index);
    if (a.indexOf(v) != -1) {
      retflag = true;
    }
    return retflag;
  }

  /**
   * 判断数组中是否有重复的元素
   * @param arr
   * @returns {boolean}
   */
  hasrepeatEl(arr: any, tablecolumns: any): boolean {
    let retflag: boolean = false;
    for (let i = 0; i < tablecolumns.length; i++) {
      const itv = tablecolumns[i];
      const isitrepeat = this.isrepeat(arr, i, itv);
      if (isitrepeat) {
        retflag = true;
        break;
      }
    }
    return retflag;
  }

  /**
   * 根据 key 去重 arr
   * @param arr
   * @param {string} key
   */
  fliterobjRepeat(arr: any, key: string) {
    let retarr = [];
    const keyarr = arr.map(function (item) {
      return item[key];
    });
    const keyonlyarr = this.fliterRepeat(keyarr);
    for (let i = 0; i < keyonlyarr.length; i++) {
      for (let j = 0; j < arr.length; j++) {
        if (keyonlyarr[i] == arr[j][key]) {
          retarr.push(arr[j]);
          break;
        }
      }
    }
    return retarr;
  }

  /**
   * 两数组去重
   * @param str
   * @param showlen
   */
  arrayRepeat(array1: any, array2: any) {
    var result = []
    for (var i = 0; i < array2.length; i++) {
      var obj = array2[i]
      var num = obj.uuid
      var isExist = false
      for (var j = 0; j < array1.length; j++) {
        var aj = array1[j]
        var n = aj.uuid
        if (n === num) {
          isExist = true
          break
        }
      }
      if (!isExist) {
        result.push(obj)
      }
    }
    return result
  }

  /**
   * 显示8个汉字，超过的用 ...显示
   * @param {string} str
   * @returns {string}
   */
  showTenchart(str: string, showlen: number): string {
    const itstr = str ? str.toString().trim() : "";
    if (itstr.length > showlen) {
      return itstr.substring(0, showlen) + "..";
    } else {
      return itstr;
    }
  }

  /**
   * 判断是什么浏览器
   * @returns {string}
   * @constructor
   */
  Browser(): string {
    let browser: string;
    const userAgent = navigator.userAgent; //取得浏览器的userAgent字符串


    const isOpera = userAgent.indexOf("Opera") > -1;//判断是否Opera浏览器
    if (isOpera) {
      browser = "Opera";
    }
    const isFirefox = userAgent.indexOf("Firefox") > -1;     //判断是否Firefox浏览器
    if (isFirefox) {
      browser = "Firefox";
    }
    const isChrome = userAgent.indexOf("Chrome") > -1;// 判断是否 Chrome 浏览器
    if (isChrome) {
      browser = "Chrome";
    }
    const isSafari = (userAgent.indexOf("Safari") > -1) && (userAgent.indexOf("Chrome") < 0);// //判断是否Safari浏览器
    if (isSafari) {
      browser = "Safari";
    }
    const isIe = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera;//判断是否IE<11浏览器
    const isEdge = userAgent.indexOf("Edge") > -1 && !isIe; //判断是否IE的Edge浏览器
    const isie11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIe || isie11 || isEdge) {
      browser = "IE";
    }
    return browser;
  }

  /**
   * 打开一个新窗口
   * @param url
   * @param winname
   * @param pro
   */
  openWin(url: string, winname: string, pro: any): void {
    let mypro: string = "";
    for (var key in pro) {
      mypro += (key + "=" + pro[key] + ",");
    }
    window.open(url, winname, mypro);
  }

  /**
   *
   * @param menulist   -----服务端返回的 菜单权限列表
   * @param {string} url  ----菜单url
   * @returns {string}  ---菜单 id
   */
  getLmenuId(menulist: any[], url: string): string {
    let menuid: string = "";
    menulist.forEach((item) => {
      if (item.code.toString().trim() === url) {
        menuid = item.id;
      }
    });
    return menuid;
  }

  /**
   *
   * @param chart
   * @param {number} jdv
   * @param {number} wdv
   * @returns {any}  [], 转换经纬度至改geo下容器的像素
   */
  convertTopixel(chart: any, jdv: number, wdv: number): any {
    // 在地里坐标系 geo上把某个点的经纬度坐标转换成为像素坐标：
    // 使用第一个 geo 坐标系进行转换：
    const pixelObjarr = chart.convertToPixel('geo', [jdv, wdv]); // 参数 'geo' 等同于 {geoIndex: 0}
    // 使用第二个 geo 坐标系进行转换：
    // this.mapchart.convertToPixel({geoIndex: 1}, [128.3324, 89.5344]);
    // 使用 id 为 'bb' 的 geo 坐标系进行转换：
    // this.mapchart.convertToPixel({geoId: 'bb'}, [128.3324, 89.5344]);
    return pixelObjarr;
  }

  /**
   * 获取大屏数据
   * @param {string} kqbh
   * @param {string} ksjhbh
   * @param {string} ksccbh
   * @param {Function} callback
   */
  getDPshowdata(kqbh: string, ksjhbh: string, ksccbh: string, callback: Function): void {
    if (!kqbh) {
      return
    }
    if (!ksjhbh) {
      return
    }
    if (!ksccbh) {
      return
    }
    const url = "jczh/fzjc/dpsjzs/1";
    this.itservice.kwPtPost(url, {
      kqbh: kqbh,
      ksjhbh: ksjhbh,
      ccm: ksccbh
    }).subscribe(resp => {
      this.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            callback(resp);
          } else {
            callback(null);
            this.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getDPshowdata(kqbh, ksjhbh, ksccbh, callback);
        }
      });
    });
  }

  /**
   * 获取大屏数据2
   * @param {Function} callback
   */
  getDPshowdata2(reqobj: any, callback: Function): void {
    const url = "jczh/fzjc/dpsjzs/fp";
    this.itservice.kwPtPost(url, reqobj).subscribe(resp => {
      this.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            callback(resp);
          } else {
            callback(null);
            this.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getDPshowdata2(reqobj, callback);
        }
      });
    });
  }

  /**
   * 阻止事件冒泡
   * @param e
   */
  stopBulbble(e: any): void {
    const isie = this.isIE();
    if (isie) {
      e.cancelBubble = true
    } else {
      e.stopPropagation();
    }
  }

  /**
   * 1： 非必填字段的去空格+ 转为""
   * 2:  必填字段的去空格
   * @param {boolean} b
   * true---yapi 定义中是 必须有的字段
   * false--yapi 定义中  非必须有的字段
   * @param {string} v
   * @returns {string}
   */
  removeSpace(b: boolean, v: string): string {
    let retstr: string = "";
    if (b) {
      retstr = v.toString().trim();
    } else {
      retstr = v ? v.toString().trim() : "";
    }
    return retstr;
  }

  /**
   * 获取 全局唯一标识符（GUID，Globally Unique Identifier）也称作 UUID(Universally Unique IDentifier) 。
   * @returns {string}
   */
  generateUUID(): string {
    let d = Date.now();
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }

  /**
   * 数组求和
   * @param arr
   * @returns {number}
   */
  sum(arr: number[]): number {
    return arr.length ? arr.reduce(function (prev, curr, idx, arr) {
      return prev + curr;
    }) : 0;
  }

  /**
   *
   * @param date   Date类型
   * @param {number} monthnum 增加的月份数
   * @returns {any}  增加月份后的Date类型
   */
  addMonth(date: any, monthnum: number): any {
    const y = date.getFullYear();
    const m = date.getMonth();
    const d = date.getDate(); // 当前日期是 第N天
    let nexty = y;
    let nextm = m;
    let nextd = d;
    // 如果当前月份+ 增加的月份大于11（m 从0开始的）
    if (m + monthnum > 11) {
      nexty = y + 1;
      nextm = Number(m + monthnum) - 12;
    } else {
      nextm = m + monthnum;
    }
    const daysinNextMonth = this.daysInMonth(nexty, nextm);

    if (d > daysinNextMonth) {
      nextd = daysinNextMonth;
    }
    return new Date(nexty, nextm, nextd);
  }

  /**
   *
   * @param year  年
   * @param month  月
   * @returns {number}  year年month月有多少天
   */
  daysInMonth(year: any, month: any): number {
    let ts: number;
    if (month == 1) {
      //2月份
      if (year % 4 == 0 && year % 100 != 0) {
        ts = 29
      } else {
        ts = 28; // 闰月
      }
    } else if ((month <= 6 && month % 2 == 0) || (month > 6 && month % 2 == 1)) {
      ts = 31
    } else {
      ts = 30;
    }
    return ts;
  }

  /**
   *
   * @param date  Date类型
   * @param {number} days  增加的天数
   * @returns {any}  增加这么多天后，新的Date
   */
  addDays(date: any, days: number): any {
    const millSeconds = date.getTime(); // ms
    const addmillSeconds = millSeconds + days * 24 * 60 * 60 * 1000;
    return new Date(addmillSeconds);
  }

  /**
   *
   * @param date1   Date类型
   * @param date2    Date类型
   * @returns {number}   两个日期之间  日期数组（到月） [yyyy-mm]
   */
  rangeDays_moth(date1: any, date2: any): any {
    const rangedayList: any[] = [];
    const byear = date1.getFullYear();
    const bmonth = date1.getMonth();
    const eyear = date2.getFullYear();
    const emonth = date2.getMonth();
    const difference_year = eyear - byear;
    const difference_month = emonth - bmonth;
    const rangemonth = difference_year * 12 + difference_month;
    rangedayList.push(this.YM_get(date1, "separate"));
    for (let i = 0; i < rangemonth; i++) {
      const addmonthdate = this.addMonth(date1, Number(i + 1));
      rangedayList.push(this.YM_get(addmonthdate, "separate"));
    }
    return rangedayList;
  }

  /**
   *
   * @param date1   Date类型
   * @param date2    Date类型
   * @returns {any} 两个日期之间的  日期数组（到天） [yyyy-mm-dd]
   */
  rangeDays_day(date1: any, date2: any): any {
    const dateArr = [];
    const sdate = date1;
    const edate = date2;
    while ((edate.getTime() - sdate.getTime()) >= 0) {
      dateArr.push(this.YMD_get(sdate));
      sdate.setDate(sdate.getDate() + 1);
    }
    return dateArr;
  }

  /**
   *
   * @param date  Date类型
   * @returns {any[]}  获取 某月的 月初和月末 Date类型 [Date, Date]
   */
  beDateBydate(date: any): any[] {
    const datesource = date;
    const fullyear = datesource.getFullYear();
    const month = datesource.getMonth();   // 0-11 ，Date函数的相关操作（获取，设置），月份的值是0-11，代表1-12月
    const endOfMonth = new Date(fullyear, month + 1, 0); // 下个月的第0天，就是本月的最后一天
    const startOfMonth = new Date(datesource.setDate(1));
    return [startOfMonth, endOfMonth];
  }


  constructor(private itservice: MyhttpService,
    private localstorage: LocalStorageService,
    private sharedService: SharedService) {
  }
}
